package com.itzol.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itzol.config.JwtTokenUtil;
import com.itzol.entity.Users;
import com.itzol.mapper.UsersMapper;
import com.itzol.service.UsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itzol.uitls.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpRequest;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author linxin
 * @since 2022-03-09
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements UsersService {
    @Autowired
    private UsersService usersService;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Override
    public Result login(String username, String password) {
        //登录逻辑
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if(passwordEncoder.matches(userDetails.getPassword(),password)){
            System.out.println(123);
        }
        if(null==userDetails||!userDetails.getPassword().equals(password)){
            return Result.fail("账号/密码错误");
        }
        if(!userDetails.isEnabled()){
            return Result.fail("账号被禁用，请联系管理员");
        }
        //更新security 用户对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails,
                null,
                userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //生成token
        String token = jwtTokenUtil.generateToken(userDetails);
        Map<String,String> tokenMap = new HashMap<>();
        tokenMap.put("tokenHead",tokenHead);
        tokenMap.put("token",token);
        return Result.succ(tokenMap);
    }
    //获取用户信息
    @Override
    public Users getUserInfo(String username) {
        return usersService.getOne(new QueryWrapper<Users>().eq("username", username).eq("status",true));
    }

}
